<?php
class Model{
	public $tabName;//存储表名用的
	public $link;//存储连接标识符用的
	public $order;//用于存储排序内容的
	public $limit;//限制取出条目需要的内容
	public $fields = '*';//用于存储表的字段名信息
	public $allFields = array();//目前是已经从数据库取出来的正规字段
	public $where;//用于存储where条件
	public function __construct($tabName){
		//连接数据库做初始化工作,一般自动执行不轻易写大量的代码,而是另外存起来,而自动执行,只做调用.
		$this->getConnect();

		$this->tabName = $tabName;

		$this->getFields();
	}

	//查询操作.
	//order by xxx desc/asc   limit x,x;
	//array('order'=>'5,10')
	public function select(){

		//php处理速度很快
		$sql = "select {$this->fields} from {$this->tabName} {$this->where} {$this->order} {$this->limit}";
		//echo $sql;exit;
		// select * from info order by id desc;
		$this->fields = '*';
		$this->where = '';
		$this->allFields = array();
		$this->order = '';
		$this->limit = '';

		return $this->query($sql);
	}

	//查询一条数据,返回一个一维数组
	public function find($id=''){
		if(empty($id)){
			$where = $this->where;
		}else{
			$where = " where id={$id}";
		}
		$sql = "select {$this->fields} from {$this->tabName} {$where}";
		//echo $sql;
		$userinfo = $this->query($sql);
		//var_dump($userinfo);
		return $userinfo[0];
	}

	//查询总共有多少条数据
	public function count(){
		$sql = "select count(*) as total from {$this->tabName}";
		$total = $this->query($sql);
		//var_dump($total);
		return $total[0]['total'];
	}

	//添加操作
	//$_POST 
	//$data['name'] = 'zhangsan';
	//array('name'=>'张三','age'=>29)
	public function add($data){
		//$sql = "insert into {$this->tabName}(xx,xx,xx....) values('','',''....)";
		
		$key = array_keys($data);
		//var_dump($key);	
		$keys = join(',',$key);
		//echo $keys;
		$value = array_values($data);
		//var_dump($value);
		$values = join("','",$value);
		//echo $values;

		$sql = "insert into {$this->tabName}({$keys}) values('{$values}')";
		//echo $sql;
		//var_dump($data);
		return $this->execute($sql);
		
	}

	//删除操作
	public function del($id=''){
		if(empty($id)){
			$where = $this->where;
		}else{
			$where = ' where id='.$id;
		}
		$sql = "delete from {$this->tabName} {$where}";
		//echo $sql;
		//删除成功先返回true,失败返回false
		return $this->execute($sql);
	
	}

	//排序 order by 字段 asc|desc  --> order('id desc');
	public function order($order){
		//$sql = "select * from "
		$this->order = 'order by '.$order;//order by id desc
		return $this;
	}

	//限制取出条目
	public function limit($limit){
		// limit 0,5
		$this->limit = ' limit '.$limit;
		return $this;
	}

	//修改操作.
	public function update($data){
		//update {$tabName} set xxx=xxx,xxx=xx where;
		
		//1.判断$data 是不是数组
		if(!is_array($data)){
			return $this;
		}

		//2.判断它是否使用id作为修改条件或者还是使用where条件作为修改.
		//array('id'=>6,'name'=>'laowang','age'=>50,'sex'=>1);
		if(!empty($data['id'])){
			$where = ' where id='.$data['id'];
		}else{
			$where = $this->where;
		}

		if(empty($where)){
			return false;
		}

		//update {$tabName} set xxx=xxx,xxx=xx where;
		foreach($data as $key=>$value){
			if($key!='id'){
				@$result .= "{$key}='{$value}',";
			}
			//rtrim
		}

		$result = rtrim($result,',');
		$sql = "update {$this->tabName} set {$result} {$where}";

		//echo $sql;
		//$info->update();
		$this->where = '';
		return $this->execute($sql);

	}

	// 
	//用于用户手动添加字段名
	public function field($fileds=array()){
		//var_dump($fileds);
		//如果你给的值是不是数组,直接返回对象
		if(!is_array($fileds)){
			return $this;
		}

		//如果有值,需要检测数据库的内容,删除没有的字段.
		$fileds_1 = $this->check($fileds);
		//echo $fileds_1;
		
		//如果$info->field()里面什么字段都不写?
		if(empty($fileds)){
			return $this;
		}


		$this->fields = '`'.join('`,`',$fileds_1).'`';



		//说明你要查询所有的字段,怎么写?
		return $this;
	}

	//自动执行的净化方法
	public function getFields(){
		//查询表信息的结构
		//desc info
		$sql = "desc {$this->tabName}";

		$result = $this->query($sql);
		//var_dump($result);exit;
		
		foreach($result as $v){
			$fields[] = $v['Field'];
		}
		//var_dump($fields);
		
		$this->allFields = $fields;
		//var_dump($fields);
	}

	//加where条件
	// select * from info where id=xx;
	// select * from info where name=xx;
	// select * from info where name like '%秋裤%';
	// select * from info where age in (40,50,60);
	// $data['id'] = 19;
	// $data['name'] = array('like','秋裤')
	// $data['age'] = array('in','40,50,60')
	// $data['age'] = array('gt','40,50,60')
	public function where($data){
		//array(name)  id>=30;
		//判断传递过来的必须是一个数组且不能为空
		if(is_array($data) && !empty($data)){
			foreach($data as $key=>$value){
				//$key 永远都是数据库中的字段名
				if(is_array($value)){
					switch($value[0]){
						case 'like':
							$result[] = "{$key} like '%{$value[1]}%'";
							break;

						case 'gt':
							$result[] = "{$key} > '{$value[1]}'";
							break;

						case 'lt':
							$result[] = "{$key} < '{$value[1]}'";
							break;

						case 'in':
							$result[] = "{$key} in ({$value[1]})";
							break;

						//如果还有新功能,在这里添加
					}
				}else{
					//如果不是数组
					//select * from info where name='laowang';
					$result[] = "{$key}"."="."'{$value}'";
					//$result[] = name='laowang';
					//$result = array(0=>"name='laowang'");
				}
			}
			$where = ' where '.join(' and ',$result);
			$this->where = $where;
		}else{
			return $this;
		}

		return $this;
	}

	public function __destruct(){
		mysqli_close($this->link);
	}

	/***************辅助工作***********************/
	public function getConnect(){
		$this->link = mysqli_connect(HOST,USER,PWD);
		if(mysqli_connect_errno($this->link)>0){
			echo mysqli_connect_error($this->link);exit;
		}
		mysqli_select_db($this->link,DB);
		mysqli_set_charset($this->link,CHARSET);
	}

	//发送语句,专门返回二维数组
	public function query($sql){
		$result = mysqli_query($this->link,$sql);
		if($result && mysqli_num_rows($result)>0){
			while($row = mysqli_fetch_assoc($result)){
				$list[] = $row;
			}
		}
		return @$list;
	}

	public function execute($sql){
		$result = mysqli_query($this->link,$sql);
		//mysqli_affected_rows --> 影响行数,上一次sql操作影响到的行数.
		if($result && mysqli_affected_rows($this->link)>0){
			//var_dump(mysqli_affected_rows($this->link));
			//如果上面if的代码不执行,让其返回true;
			

			//这一块代码,主要用于insert添加操作,让其返回操作的id
			if(mysqli_insert_id($this->link)){
				return mysqli_insert_id($this->link);
			}


			return true;
		}else{
			return false;
		}
	}


	//检测字段的方法,回首看117行.
	public function check($arr){
		//var_dump($arr);
		foreach($arr as $k=>$v){
			//echo $k;
			//echo $v;
			if(!in_array($v,$this->allFields)){
				unset($arr[$k]);
			}			
		}
		return $arr;
	}
}



